import PropTypes from 'prop-types';
import PureRenderMixin from "react-addons-pure-render-mixin"
import React, {Component} from 'react';
import * as d3 from 'd3';

import T from 'utils/T';


@T.decorator.propTypes({
    options: PropTypes.object,
    data: PropTypes.array
})
export default class D3Chart extends Component {
    static defaultProps = {
        data: []
    };

    constructor(props) {
        super(props);

        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.chart = null;
        this.data = [];
    }

    componentDidMount() {
        this.normalize();
        this.isDraw();
    }

    /**
     * 刷新数据
     * @param nextProps
     */
    componentWillReceiveProps(nextProps) {
        if (nextProps.data) {
            this.isDraw();
        }
    }

    componentDidUpdate(nextProps) {
        if (nextProps.data) {
            this.isDraw();
        }
    }

    /**
     * 标准化数据格式
     */
    normalize() {
        this.xData = this.props.data;
    }

    setDefaultOptions(){
        return {
            width: 400,
            height: 400,
            color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3']
        }
    }

    getOptions(){
        return Object.assign({}, this.setDefaultOptions(), this.props.options)
    }

    isDraw() {
        if (this.wrapper) {

            this.drawChart();
        }
    }

    drawChart(){
        const options = this.getOptions();
        this.chart = d3.select(this.wrapper)     //选择文档中的wrapper元素
            .append('svg')          //添加一个svg元素
            .attr('width', '100%')       //设定宽度
            .attr('height', options.height)    //设定高度
            .style('border', '1px solid #ccc');

    }

    render() {
        const options = this.getOptions();
        return (
            <div className="d3chart">
                <div className="d3chart-content"
                     style={{width: '100%', height: options.height}}
                     ref={wrapper => (this.wrapper = wrapper)}
                />
            </div>
        )
    }
}
